<?php

namespace app\web\controller;

use app\common\controller\Frontend;
use app\common\model\customer\Customer as customerModel;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\purchase\Goods as Gmodel;
use app\common\model\sales\CheckoutGoods;
use app\common\model\sales\Goods as sGoods;
use app\common\model\sales\Slip;
use think\Db;
use think\Exception;
use app\web\controller\Wweixin;

class Sales extends Frontend
{

    protected $noNeedLogin = '';
    protected $noNeedRight = 'index,detail,getslips';
    protected $layout = '';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\sales\Slip;
    }

    //创建销售单
    public function confirm(){
        //获取默认仓库或者所属仓库
        if(session('admin')['storehouse_id'] >0){
            $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
        }else{
            $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
        }
        $c_id = input('c_id/d',0);
        if(empty($c_id)){
            $this->error('尚未选择客户','customer/choose?ids='.input('cart_ids'));
        }
        $model = new customerModel;
        $row = $model->where(array('id'=>$c_id))->find();
        if(empty($row)){
            $this->error('尚未选择客户','customer/choose?ids='.input('cart_ids'));
        }
        $tax = input('tax/d',0);
        if ($this->request->isAjax()) {
            $params = input();
            $address = '';
            $mobile = '';
            $contacts = '';
            if(isset($params['crow']) && !empty($params['crow'])){
                $address = $params['crow'][0]['address'];
                $mobile = $params['crow'][0]['mobile'];
                $contacts = $params['crow'][0]['contacts'];
            }
            if(!isset($params['datas'])){
                $this->error('数据异常');
            }
            if(count($params['datas']) < count($params['cart_ids'])){
                $this->error('数据不全');
            }
            $c_id = $params['c_id'];//客户ID
            $tax = $params['tax']; //税点
            $explain = $params['explain']; //备注说明
//            $is_buy = $params['is_buy']; //是否自动请购

            if($tax >13){
                $this->error('请检查税费');
            }
            $sale_num= 0;
            $actual_cost = 0;
            foreach ($params['datas'] as $k=> $v){
                 $info = Db::name('sales_cart')->where(array('id'=>$v['id']))->find();
                 if(empty($info)){
                     $this->error('购物车商品不存在');
                 }
                 $sale_num+=$info['num'];
                 $sfhj = bcmul($info['num'],$v['ht_price'],2);
                 $params['datas'][$k]['sfhj'] = $sfhj;
                 $actual_cost = bcadd ($sfhj,$actual_cost,2);
            }

            //获取默认仓库或者所属仓库
            if(session('admin')['storehouse_id'] >0){
                $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            }else{
//                $this->error('无归属仓库');
                $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            }

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $num = Db::name('sales_slip')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $saledata = array(
                'number'=>'XD-T-'.date('Y-m-d').'-'.getnumber($num),
                'sales_type_id'=>3,
                'sales_number'=>'',
                'actual_cost'=>$actual_cost,
                'customer_id'=>$c_id,
                'storehouse_id'=>$hrow['id'],
                'explain'=>$explain,
                'address'=>$address,
                'mobile'=>$mobile,
                'contacts'=>$contacts,
                'tax'=>$tax,
                'sales_num'=>$sale_num,
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'deliverytime'=>time(),
            );
            $saledata['status'] = 7;

            Db::startTrans();
            try {
                $this->model->save($saledata);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$hrow['id'],
                    'bill_id'=>$this->model->id,
                    'type'=>6,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                if(!$this->model->id){
                    throw new Exception('添加失败');
                }

                $gdata = [];
                foreach ($params['datas'] as $k => $v) {
                    $info = Db::name('sales_cart')->where(array('id'=>$v['id']))->find();
                    $gdata[] = array(
                        'goods_id' => $info['goods_id'],
                        'goods_num' => $info['num'],
                        'sale_price' => bcdiv($v['ht_price'],(1+$tax/100),2),
                        'ht_price' => $v['ht_price'],
                        'sfhj'=>$v['sfhj'],
                        'tax' => $tax,
                        'storehouse_id' => $hrow['id'],
                        'customer_id' => $c_id,
                        'sales_slip_id' => $this->model->id,
                        'createtime'=>time(),
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                    Db::name('goods')->where(array('id'=>$info['goods_id']))->setInc('weigh');
                    Db::name('sales_cart')->where(array('id'=>$v['id']))->delete();
                }
                $sGoods = new sGoods;
                $sGoods->saveAll($gdata);

                if(isset($saledata['status']) && $saledata['status'] ==7){

                }else{
                    $wx = new Wweixin;
                    $wx->senmsg(6);
                }
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'创建成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $cart_ids = explode('-',input('cart_ids',''));
        if(empty($cart_ids)){
            $this->error('尚未选择商品','goods/cart');
        }

        $list = Db::name('sales_cart')
            ->field('c.id,c.num,g.title,g.specs,b.name,g.number')
            ->where(array('c.id'=>array('in',$cart_ids)))
            ->alias('c')
            ->join('goods g','c.goods_id = g.id')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();
        $allnum = 0;
        $numbers = [];
        foreach ($list as $v){
            $numbers[] = $v['number'];
            $allnum += $v['num'];
        }
        $prices = $this->getprice(implode(',',$numbers),$hrow['code']);
        foreach ($list as &$v){
            $v['price'] = 0;
        }


        $this->assign('cart_ids',input('cart_ids',''));
        $this->assign('list',$list);
        $this->assign('allnum',$allnum);
        $this->assign('row',$row);
        $this->assign('tax',$tax);
        $this->assign('c_id',$c_id);
        return $this->view->fetch();
    }
    public function index(){
        $keywords = input('keywords');

        $model = new Slip;
        $status = $model->slip_status();
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];

        $where  = array('storehouse_id'=>$storehouse_id);
        if(!empty($keywords)){
            $cwhere['nickname']  = array('like','%'.$keywords.'%');
            $cids = Db::name('customer')->where($cwhere)->column('id');
           if(!empty($cids)){
               $where['c.id'] = array('in',$cids);
           }
        }


        $list = Db::name('sales_slip')
            ->field('s.id,s.number,explain,s.operator,s.company,sales_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->where($where)
            ->limit(0,10)
            ->order('s.id','DESC')
            ->select();
        $total = Db::name('sales_slip')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->where($where)
            ->count();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }
        $this->assign('keywords',$keywords);
        $this->assign('total',$total);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function getslips(){

        $page = input('page/d',1);
        $status = input('status/d',0);
        $pagesize = input('pagesize/d',10);
        $keywords = input('keywords');
        if(!empty($keywords)){
            $cwhere['nickname']  = array('like','%'.$keywords.'%');
            $cids = Db::name('customer')->where($cwhere)->column('id');
            if(!empty($cids)){
                $where['c.id'] = array('in',$cids);
            }
        }

        $where = [];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
        $where['storehouse_id'] = $storehouse_id;
        if($status){
            if($status == 2){
                $where['s.status'] = array('in',[2,3]);
            }else{
                $where['s.status'] = $status;
            }
        }
        if(isset($where['s.status']) && $where['s.status'] == 7){
            $where['admin_id'] = session('admin')['id'];
        }

        $model = new Slip;
        $status = $model->slip_status();
        $list = Db::name('sales_slip')
            ->field('s.id,s.number,explain,s.operator,s.company,sales_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->limit($page*$pagesize,$pagesize)
            ->where($where)
            ->order('s.id','DESC')
            ->select();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }
        $this->success('','',$list);
    }

    //需加判断
    public function edit(){
        $ids =input('ids/d',0);
        $model = new Slip();
        $row = $model->find($ids);
        if(empty($ids) || empty($row)){
            $this->error('查无数据');
        }
        if($this->request->isAjax()){
            $tax = floatval(input('tax'));
            if(!is_float($tax) || $tax >17){
                $this->error('请检查税费');
            }
            $explain = input('explain');
            $datas = input('datas/a');

            Db::startTrans();
            try {
                $sales_num = 0;
                $actual_cost = 0;
                foreach ($datas as $v) {
                    $sfhj = bcmul($v['ht_price'],$v['goods_num'],2);
                    Db::name('sales_goods')->where(array('id' => $v['id']))->update(array(
                        'goods_num' => $v['goods_num'],
                        'ht_price' => $v['ht_price'],
                        'sfhj' => $sfhj,
                        'sale_price' => $v['ht_price'] / (1 + $tax / 100),
                        'tax' => $tax,
                    ));
                    $actual_cost += $sfhj;
                    $sales_num+=$v['goods_num'];
                }

                $model = new Slip();
                $model->save(array('tax' => $tax, 'explain' => $explain,'actual_cost'=>$actual_cost,'sales_num'=>$sales_num), array('id' => $ids));
                Db::commit();
                return array(
                    'code' => 1,
                    'msg' => '成功'
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $list = Db::name('sales_goods')
            ->where(array('c.sales_slip_id'=>$ids))
            ->field('c.id,title,specs,goods_num,ht_price,tax')
            ->alias('c')
            ->join('goods g','c.goods_id = g.id','LEFT')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();

        $crow = \app\common\model\customer\Customer::find($row['customer_id']);

        $contacts = empty($row['contacts'])?$crow['contacts']:$row['contacts'];
        $mobile = empty($row['mobile'])?$crow['mobile']:$row['mobile'];
        $address = empty($row['address'])?$crow['address']:$row['address'];

        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('contacts',$contacts);
        $this->assign('mobile',$mobile);
        $this->assign('address',$address);
        $this->assign('count',count($list));
        return $this->view->fetch();
    }
    public function detail(){
        $ids =input('ids/d',0);
        $model = new Slip();
        $row = $model->find($ids);
        if(empty($ids) || empty($row)){
            $this->error('查无数据');
        }
        if ($this->request->isAjax()) {
//            $this->success('1');
            if($row['status'] !=1){
                $this->error('状态异常');
            }
            $status = input('status/d',0);
            if(!$status){
                $this->error('非法操作');
            }
            Db::startTrans();
            try {
                $res = $this->model->save(array('status' => $status), array('id' => $ids));
                if ($res) {
                    $type = 1;
                    if($status == 6){ //审核拒绝
                        $type = 2;
                        $sGoods = new sGoods;
                        $ress = $sGoods->save(array('status'=>5),array('sales_slip_id'=>$ids));
                        if (!$ress) {
                            throw new Exception('数据异常');
                        }
                    }

                    Db::name('examine_log')->insert(array(
                        'admin_id'=>session('admin')['id'],
                        'type'=>$type,
                        'createtime'=>time(),
                        'controller'=>'sales/slip',
                        'source_id'=>$ids,
                        'source'=>6,
                        'remark'=>'销售单',
                        'number'=>isset($row['number'])?$row['number']:'',
                    ));

                    if($status  == 2){
                        //添加记录
                        $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                            'customer_id'=>$row['customer_id'],
                            'type'=>'销售单',
                            'type_id'=>1,
                            'number'=>$row['number'],
                            'source_id'=>$row['id'],
                            'createtime'=>time(),
                            'admin_id'=>$row['admin_id'],
                            'group_id'=>$row['group_id'],
                            'company'=>$row['company'],
                            'operator'=>$row['operator'],
                            'sales_num'=>$row['sales_num'],
                            'actual_cost'=>$row['actual_cost'],
                            'storehouse_id'=>$row['storehouse_id'],
                        ));
                        if(empty($sales_log_id)){
                            throw new Exception('数据异常');
                        }

                        $glists = Db::name('sales_goods')->where(array('sales_slip_id'=>$ids))->select();
                        foreach ($glists as $v){
                            Db::name('goods_sales_log')->insert(array(
                                'goods_id'=>$v['goods_id'],
                                'type'=>'销售单',
                                'type_id'=>1,
                                'number'=>$row['number'],
                                'source_id'=>$row['id'],
                                'createtime'=>time(),
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'storehouse_id'=>$row['storehouse_id'],
                                'sales_log_id'=>$sales_log_id,
                            ));
                        }
                    }
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $list = Db::name('sales_goods')
            ->where(array('c.sales_slip_id'=>$ids))
            ->alias('c')
            ->join('goods g','c.goods_id = g.id','LEFT')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();

        $crow = \app\common\model\customer\Customer::find($row['customer_id']);

        $contacts = empty($row['contacts'])?$crow['nickname']:$row['contacts'];
        $mobile = empty($row['mobile'])?$crow['mobile']:$row['mobile'];
        $address = empty($row['address'])?$crow['address']:$row['address'];


        $this->assign('ids',$ids);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('contacts',$contacts);
        $this->assign('mobile',$mobile);
        $this->assign('address',$address);
        return $this->view->fetch();
    }
    public function checkout(){
        $ids =input('ids/d',0);
        $model = new Slip();
        $row = $model->find($ids);
        if(empty($ids) || empty($row)){
            $this->error('查无数据');
        }

        $list = Db::name('sales_goods')
            ->where(array('c.sales_slip_id'=>$ids))
            ->alias('c')
            ->field('c.id,goods_num,specs,ht_price,tax,goods_num,goods_id,title')
            ->join('goods g','c.goods_id = g.id','LEFT')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();

        $crow = \app\common\model\customer\Customer::find($row['customer_id']);

        $contacts = empty($row['contacts'])?$crow['contacts']:$row['contacts'];
        $mobile = empty($row['mobile'])?$crow['mobile']:$row['mobile'];
        $address = empty($row['address'])?$crow['address']:$row['address'];

        foreach ($list as $k => $v){
//            $GoodsHouseStock = new GoodsHouseStock;
//            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
//            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
            $checkoutgoods = new CheckoutGoods();
            $list[$k]['cnum'] = $checkoutgoods->where(array('goods_id'=>$v['goods_id'],'sales_slip_id'=>$row['id'],'status'=>array('>',0)))->sum('goods_num');
        }

        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('contacts',$contacts);
        $this->assign('mobile',$mobile);
        $this->assign('address',$address);
        return $this->view->fetch();
    }
    public function examine(){
        $ids = input('sid/d',0);
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        if ($this->request->isAjax()) {
            $status = input('status/d',0);
            if(!$status){
                $this->error('非法操作');
            }
            Db::startTrans();
            try {
                $res = $this->model->save(array('status' => $status), array('id' => $ids));
                if ($res) {
                    $type = 1;
                    if($status == 6){ //审核拒绝
                        $type = 2;
                        $sGoods = new sGoods;
                        $ress = $sGoods->save(array('status'=>5),array('sales_slip_id'=>$ids));
                        if (!$ress) {
                            throw new Exception('数据异常');
                        }
                    }

                    Db::name('examine_log')->insert(array(
                        'admin_id'=>session('admin')['id'],
                        'type'=>$type,
                        'createtime'=>time(),
                        'controller'=>'sales/slip',
                        'source_id'=>$ids,
                        'source'=>6,
                        'remark'=>'销售单',
                        'number'=>isset($row['number'])?$row['number']:'',
                    ));

                    if($status  == 2){
                        //添加记录
                        $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                            'customer_id'=>$row['customer_id'],
                            'type'=>'销售单',
                            'type_id'=>1,
                            'number'=>$row['number'],
                            'source_id'=>$row['id'],
                            'createtime'=>time(),
                            'admin_id'=>$row['admin_id'],
                            'group_id'=>$row['group_id'],
                            'company'=>$row['company'],
                            'operator'=>$row['operator'],
                            'sales_num'=>$row['sales_num'],
                            'actual_cost'=>$row['actual_cost'],
                            'storehouse_id'=>$row['storehouse_id'],
                        ));
                        if(empty($sales_log_id)){
                            throw new Exception('数据异常');
                        }

                        $glists = Db::name('sales_goods')->where(array('sales_slip_id'=>$ids))->select();
                        foreach ($glists as $v){
                            Db::name('goods_sales_log')->insert(array(
                                'goods_id'=>$v['goods_id'],
                                'type'=>'销售单',
                                'type_id'=>1,
                                'number'=>$row['number'],
                                'source_id'=>$row['id'],
                                'createtime'=>time(),
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'storehouse_id'=>$row['storehouse_id'],
                                'sales_log_id'=>$sales_log_id,
                            ));
                        }
                    }
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }
}
